<template>
  <PageWrapper class="ztable" contentFullHeight>
    <vxe-grid ref='xGrid' v-bind="gridOptions">
      <template #tbtns>
        <span style="color: #0915f1;margin-left: 2px;margin-right: 10px;display: inline-block">表名：{{table.name}}</span>
        <vxe-input v-model="formData.name" placeholder="输入名称查询"></vxe-input>
        <vxe-button @click="searchEvent" status="primary">查 询</vxe-button>
        <vxe-button @click="insertEvent(-1)">新 增</vxe-button>
<!--        <vxe-button @click="deleteEvent($refs.xGrid)">删 除</vxe-button>-->
      </template>
      <template #pager>
        <vxe-pager
            :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
            v-model:current-page="tablePage.currentPage"
            v-model:page-size="tablePage.pageSize"
            :total="tablePage.total"
            @page-change="handlePageChange">
        </vxe-pager>
      </template>
    </vxe-grid>
    <FieldDrawer @register="registerDrawer" @success="handleSuccess"/>
  </PageWrapper>
</template>
<script lang="ts">
export default {name: 'BiFieldMain', inheritAttrs: false}
</script>
<script lang="ts" setup>
import {PageWrapper} from '/@/components/Page';
import {onMounted, reactive, ref} from 'vue'
import {VXETable, VxeGridInstance, VxeGridProps,VxePagerEvents} from 'vxe-table'
import FieldDrawer from './FieldDrawer.vue';
import {useDrawer} from '/@/components/Drawer';
import {deleteEvent, addEvent, editEvent, createOption} from '/@/comps/vxe/list';
import {useRoute} from 'vue-router';
import {defHttp} from "/@/utils/http/axios";
import XEUtils from 'xe-utils'


const route = useRoute();
const tableid = ref(route.params?.id);
const table = ref({});

async function fetch() {
  table.value = await defHttp.get({url: '/bi/table/main/one/' + tableid.value});
}

const tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

const xGrid = ref({} as VxeGridInstance)

const formData = reactive({name: '',tableid})

const gridOptions = reactive<VxeGridProps>({
  border: true,
  resizable: true,
  showHeaderOverflow: true,
  showOverflow: true,
  highlightHoverRow: true,
  keepSource: true,
  id: 'full_edit_1',
  height: 600,
  rowId: 'id',
  data: [
    { id: 10001, name: 'Test1', nickname: 'T1', role: 'Develop', sex: '1', age: 28, address: 'Shenzhen' },
    { id: 10002, name: 'Test2', nickname: 'T2', role: 'Test', sex: '0', age: 22, address: 'Guangzhou' },
    { id: 10003, name: 'Test3', nickname: 'T3', role: 'PM', sex: '1', age: 32, address: 'Shanghai' },
    { id: 10004, name: 'Test4', nickname: 'T4', role: 'Designer', sex: '0', age: 23, address: 'Shenzhen' },
    { id: 10005, name: 'Test5', nickname: 'T5', role: 'Develop', sex: '0', age: 30, address: 'Shanghai' },
  ],
  customConfig: {
    storage: true,
    checkMethod({column}) {
      if (['nickname', 'role'].includes(column.property)) {
        return false
      }
      return true
    }
  },
  sortConfig: {
    trigger: 'cell',
    remote: true
  },
  filterConfig: {
    remote: true
  },
  pagerConfig: {
    pageSize: 10,
    pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000]
  },
  toolbarConfig: {
    slots: {buttons: 'tbtns'},
    // buttons: [
    //   {code: 'insert', name: '新增', icon: 'fa fa-plus'},
    //   {code: 'delete', name: '直接删除', icon: 'fa fa-trash-o'},
    //   {code: 'mark_cancel', name: '删除/取消', icon: 'fa fa-trash-o'},
    //   {code: 'save', name: '保存', icon: 'fa fa-save', status: 'success'}
    // ],
    refresh: true,
    custom: true
  },
  // proxyConfig: {
  //   seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
  //   sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
  //   filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
  //   form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
  //   // 对应响应结果 { result: [], page: { total: 100 } }
  //   props: {
  //     result: 'result', // 配置响应结果列表字段
  //     total: 'page.total' // 配置响应结果总页数字段
  //   },
  //   // 只接收Promise，不关心系实现方式
  //   ajax: {
  //     // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
  //     query: ({page, sorts, filters, form}) => {
  //       const queryParams: any = Object.assign({}, form)
  //       // 处理排序条件
  //       const firstSort = sorts[0]
  //       if (firstSort) {
  //         queryParams.sort = firstSort.property
  //         queryParams.order = firstSort.order
  //       }
  //       // 处理筛选条件
  //       filters.forEach(({property, values}) => {
  //         queryParams[property] = values.join(',')
  //       })
  //       // return fetch(`https://api.xuliangzhan.com:10443/demo/api/pub/page/list/${page.pageSize}/${page.currentPage}`, queryParams).then(response => {
  //       //   return response.json()
  //       // })
  //       return defHttp.post('https://api.xuliangzhan.com:10443/demo/api/pub/save')
  //     },
  //     // 当点击工具栏删除按钮或者手动提交指令 delete 时会被触发
  //     delete: ({body}) => {
  //       return defHttp.post('https://api.xuliangzhan.com:10443/demo/api/pub/save', body)
  //     },
  //     // 当点击工具栏保存按钮或者手动提交指令 save 时会被触发
  //     save: ({body}) => {
  //       return defHttp.post('https://api.xuliangzhan.com:10443/demo/api/pub/save', body)
  //     }
  //   }
  // },
  columns: [
    // {type: 'checkbox', title: 'ID', width: 120},
    {type: 'checkbox', align: 'center', width: 42, fixed: 'left'},
    {type: 'seq', align: 'center', width: 50, fixed: 'left'},
    {field: 'name', title: '字段名',width: 300, sortable: true, editRender: {name: 'input'}
    },
    {field: 'comet', title: '字段注释',width: 300,  sortable: true, editRender: {name: 'input'}
    },
    {
      field: 'type', title: '字段类型',width: 150, editRender: {name: '$select', options: [], props: {placeholder: '请选择类型'}}
    },
    {field: 'length', title: '字段长度',width: 100, editRender: {name: '$input', props: {type: 'number'}}},
    {field: 'comet', title: '其他说明',editRender: {name: 'input'}},
    {
      field: 'crtim', title: '创建时间', width: 160, visible: false,
      formatter({cellValue}) {
        return XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
      }
    },
    {
      field: 'uptim', title: '更新时间', width: 160, visible: false,
      formatter({cellValue}) {
        return XEUtils.toDateString(cellValue, 'yyyy-MM-dd HH:ss:mm')
      }
    }
  ],
  checkboxConfig: {
    // labelField: 'id',
    // reserve: true,
    // highlight: true,
    range: true
  },
  editRules: {
    name: [
      {required: true, message: '字段名必须填写'},
    ],
  },
  editConfig: {
    trigger: 'click',
    mode: 'row',
    showStatus: true
  }
})

const insertEvent = async (row: any) => {
  const $grid = xGrid.value
  const record = {
    sex: '1',
    date12: '2021-01-01'
  }
  const { row: newRow } = await $grid.insertAt(record, row)
  await $grid.setActiveCell(newRow, 'name')
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
  tablePage.currentPage = currentPage
  tablePage.pageSize = pageSize
  findList()
}


const findList = () => {
  gridOptions.loading = true
  setTimeout(() => {
    gridOptions.loading = false
    tablePage.total = 10
    gridOptions.data = [
      { id: 10001, name: 'Test1', nickname: 'T1', role: 'Develop', sex: '1', age: 28, address: 'Shenzhen' },
      { id: 10002, name: 'Test2', nickname: 'T2', role: 'Test', sex: '0', age: 22, address: 'Guangzhou' },
      { id: 10003, name: 'Test3', nickname: 'T3', role: 'PM', sex: '1', age: 32, address: 'Shanghai' },
      { id: 10004, name: 'Test4', nickname: 'T4', role: 'Designer', sex: '0', age: 23, address: 'Shenzhen' },
      { id: 10005, name: 'Test5', nickname: 'T5', role: 'Develop', sex: '0', age: 30, address: 'Shanghai' },
      { id: 10006, name: 'Test6', nickname: 'T6', role: 'Develop', sex: '0', age: 27, address: 'Shanghai' },
      { id: 10007, name: 'Test7', nickname: 'T7', role: 'Develop', sex: '1', age: 29, address: 'Shenzhen' },
      { id: 10008, name: 'Test8', nickname: 'T8', role: 'Develop', sex: '0', age: 32, address: 'Shanghai' },
      { id: 10009, name: 'Test9', nickname: 'T9', role: 'Develop', sex: '1', age: 30, address: 'Shenzhen' },
      { id: 10010, name: 'Test10', nickname: 'T10', role: 'Develop', sex: '0', age: 34, address: 'Shanghai' }
    ]
  }, 300)
}

onMounted(() => {
  const typeList = [
    {label: '女', value: '0'},
    {label: '男', value: '1'}
  ]
  const {columns} = gridOptions
  if (columns) {
    const typeColumn = columns[4]
    if (typeColumn && typeColumn.editRender) {
      typeColumn.editRender.options = typeList
    }
  }
})

const searchEvent = () => {
  xGrid.value.commitProxy('query')
}

onMounted(() => {
  fetch();
});

//--------------------------------------------------------------------------------------------------
const [registerDrawer, {openDrawer}] = useDrawer();

</script>

